package com.lftea.dao.impl;

import java.sql.Date;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;

import com.lftea.dao.ISaleDAO;
import com.lftea.po.Employee;
import com.lftea.po.Sale;

@Repository("saleDAOImpl")
public class SaleDAOImpl implements ISaleDAO {
	
	@Resource(name = "jdbcTemplate")
	private JdbcTemplate jdbcTemplate;

	@Resource(name = "employeeDAOImpl")
	private EmployeeDAOImpl employeeDAOImpl;

	public List<Sale> findAll() {
		String sql = "select * from Sale";
		return jdbcTemplate.query(sql, new SaleMapper());
	}

	public Sale findById(long saveId) {
		String sql = "select * from Sale where Sale_ID=?";
		return (Sale) jdbcTemplate.query(sql, new Object[] { saveId },
				new SaleMapper());
	}

	public void remove(Sale sale) {
		// TODO 先删除细单
		// 再删除总单
		long saleId = sale.getId();
		String sql = "delete * Sale where Sale_ID=?";
		jdbcTemplate.update(sql, new Object[] { saleId });
	}

	public void save(Sale sale) {
		long saleId = sale.getId();
		Employee employee = sale.getEmployee();
		Date saleDate = sale.getSaleDate();
		long employeeId = employee.getId();

		String sql = "select count(*) from Sale where Sale_ID=?";
		int result = jdbcTemplate.queryForInt(sql, new Object[] { saleId });
		Object[] params = null;
		if (result > 0) {
			sql = "update Sale set Employee_ID=?,SaleDate=?,Employee_ID=? where Sale_ID=?";
			params = new Object[] { employeeId, saleDate, employeeId };
		} else {
			sql = "insert into Sale(SaleDate,Employee_ID) values(?,?)";
			params = new Object[] { employeeId, saleDate };
		}
		jdbcTemplate.update(sql, params);
	}

	private final class SaleMapper implements RowMapper<Sale> {

		public Sale mapRow(ResultSet rs, int rowNum) throws SQLException {
			Sale sale = new Sale();
			long saleId = rs.getLong("Sale_ID");
			sale.setId(saleId);
			sale.setSaleDate(rs.getDate("saleDate"));
			long employeeId = rs.getLong("Employee_ID");
			Employee employee = employeeDAOImpl.findById(employeeId);
			sale.setEmployee(employee);
			return sale;
		}

	}
}
